<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 章节数据模型
 * 
 * @author 陈蕾
 */
class Model_Chapter extends ORM
{
	const TABLE = 'chapter';
	
	// Model table information
    protected $_table_name = 'chapter';
    
    // Table primary key and value
	protected $_primary_key  = 'id';
	protected $_primary_val  = 'name';
	
	// Validation members
    protected $_filters = array(
    	'order' => array(
    		'intval' => NULL
    	)
    );
    
    protected $_rules = array(
        'name'=> array(
            'not_empty' => NULL,
            'max_length' => array('20')
        )
    );
	
	/**
	 * 获取当前章节的下一个章节
	 * 
	 * @return array 章节的详细数据
	 */
	public function getNext()
	{
		$record = DB::select()
			->from(self::TABLE)
			->where('order', '>=', $this->order)
			->and_where('id', '!=', $this->id)
			->order_by('id', 'ASC')
			->limit(1)
			->execute()
			->current();
		
		if (!$record) {
			return array();
		}
		return $record;
	}
	
	/**
     * 获取数据总数
     */
    public static function getCount()
    {
    	return DB::select(DB::expr('COUNT(*) AS total'))
			->from(self::TABLE)
			->execute()
			->get('total');
    }
	
	/**
     * 判断章节ID是否有效
     */
	public static function exists($value)
    {
        return (bool)DB::select(array('COUNT("*")', 'total_count'))
            ->from(self::TABLE)
            ->where('id', '=', $value)
            ->execute()
            ->get('total_count');
    }
	
	/**
	 * 获取第一个章节
	 * 
	 * @return array 章节的详细数据
	 */
	public static function getFirst()
	{
		$record = DB::select()
			->from(self::TABLE)
			->order_by('order', 'ASC')
			->order_by('id', 'ASC')
			->limit(1)
			->execute()
			->current();
		
		if (!$record) {
			return array();
		}
		return $record;
	}
	
	/**
	 * 获取章节列表
	 */
	public static function getList()
	{
		return DB::select()->from(self::TABLE)
			->order_by('order', 'ASC')->execute()->as_array();
	}
}